﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Drawing;

namespace LPT_5.Flickr
{
    class FlickClient
    {
        private String[] FLICKR_IP = { "68.142.214.24","77.238.161.100", "77.238.161.100", "76.13.18.70", "76.13.18.77", "67.215.65.132" };
        private const int FLICKR_PORT = 80;
        private const String FLICKR_KEY = "0f8123e52f601560f3eb7c0c0c790b8a";
        private const String FLICKR_SECRET = "c976a90f5a682f6b";

        private HTTPSocket.Socket hsAPISock = null;

        public FlickClient()
        {
            hsAPISock = new LPT_5.HTTPSocket.Socket(FLICKR_IP[0], FLICKR_PORT);
            hsAPISock.AddHeader("User-Agent", "FlickClient/C#");
        }

        public XmlDocument GetImagesByTag(String sTag)
        {
            String sResult = DoAPIRequest("/services/rest/?method=flickr.photos.search&api_key=" + FLICKR_KEY + "&tags="+sTag);

            XmlDocument xdResult = new XmlDocument();
            xdResult.LoadXml(sResult);
            return xdResult;
        }

        public Image ExtractImage(XmlNode xnData)
        {
            try
            {
                XmlAttributeCollection xacAttribs = xnData.Attributes;

                String sFarm = GetFarmIP(Convert.ToInt32(xacAttribs["farm"].Value));
                String sServer = xacAttribs["server"].Value;
                String sId = xacAttribs["id"].Value;
                String sSecret = xacAttribs["secret"].Value;

                String sImgUrl = "/" + sServer + "/" + sId + "_" + sSecret + "_b.jpg";

            
                HTTPSocket.Socket s = new LPT_5.HTTPSocket.Socket(sFarm, FLICKR_PORT);
                byte[] bImg = s.GetRaw(sImgUrl);
                MemoryStream ms = new MemoryStream(bImg);
                Image returnImage = Image.FromStream(ms);
                return returnImage;
            }
            catch (Exception e)
            {
                return null;
            }
        }

        private String DoAPIRequest(String sAPIReq)
        {
            return hsAPISock.GetURL(sAPIReq);
        }

        public String GetFarmIP(int iFarmNum)
        {
            return FLICKR_IP[iFarmNum];
        }
    }
}
